﻿using DataChangeTools.Api.Models;
using Newtonsoft.Json;
using RestSharp;
using System;


namespace DataChangeTools.Api.Service
{
    public class HttpRestClient
    {
        private readonly string apiUrl;
        protected readonly RestClient client;

        public HttpRestClient(string apiUrl)
        {
            this.apiUrl = apiUrl;
            client = new RestClient();
        }
        public async Task<HttpResponseDTO> ExecuteAsync(BaseRequest baseRequest)
        {
            var request = new RestRequest(new Uri(apiUrl + baseRequest.Route), baseRequest.Method);
            request.AddHeader("Content-Type", baseRequest.ContentType);
            request.AddHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36");
            if (baseRequest.Parameter != null)
                request.AddStringBody(JsonConvert.SerializeObject(baseRequest.Parameter), DataFormat.Json);
            var response = await client.ExecuteAsync(request);
            return JsonConvert.DeserializeObject<HttpResponseDTO>(response.Content);
        }
        public async Task<HttpResponseDTO<T>> ExecuteAsync<T>(BaseRequest baseRequest)
        {
            var request = new RestRequest(new Uri(apiUrl + baseRequest.Route), baseRequest.Method);
            request.AddHeader("Content-Type", baseRequest.ContentType);
            request.AddHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36");
            if (baseRequest.Parameter != null)
            {
                //request.AddJsonBody(baseRequest.Parameter);
                request.AddStringBody(JsonConvert.SerializeObject(baseRequest.Parameter), DataFormat.Json);
               
                //request.AddBody(JsonConvert.SerializeObject(baseRequest.Parameter), ContentType.Json);
            }

            var response = await client.ExecuteAsync(request);
            var a = JsonConvert.DeserializeObject<HttpResponseDTO<T>>(response.Content);
            return a;


        }
    }
}
